﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.ActiveRecord;
using System.Reflection;
using System.Configuration;
using Castle.ActiveRecord.Framework;
using System.Threading;
using Longtop.Web.WebSite.Models;
using Longtop.Web.SaleWeb.Models;
using System.ComponentModel.DataAnnotations;
namespace Longtop.Web.WebSite
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                 "Default",                                              // Route name
                    "{controller}/{action}/{id}",      // URL with parameters
                 new { controller = "Home", action = "Index", id = "" },// Parameter defaults
                  new[] { "Longtop.Web.SaleWeb.Controllers", "Longtop.Web.WebSite.Controllers" }
             );
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);
            log4net.Config.XmlConfigurator.Configure();
            InterceptorFactory.Create = () =>
            {
                return new DataMutiLanguageInterceptor();
            };

            ActiveRecordStarter.Initialize(ConfigurationManager.GetSection("activerecord") as IConfigurationSource
                ,
                new[] 
                { 
                    typeof(Sale), 
                    typeof(Achievement), 
                    typeof(Case),
                    typeof(Lable), 
                    typeof(Role), 
                    typeof(RolePermission)
                }
                );

            SetAllActions();

            DataAnnotationsModelValidatorProvider.RegisterAdapter(
    typeof(RemoteAttribute),
    typeof(RemoteAttributeAdapter)
);
        }

        public void SetAllActions()
        {
            RolePermission.Actions = new Dictionary<string, RolePermission>();
            RolePermission.Actions.Clear();
            var types = Assembly.GetAssembly(typeof(Admin.Controllers.ControllerBase)).GetTypes();

            foreach (var type in types)
            {
                if (type.BaseType != null && type.BaseType.Name == "ControllerBase")//如果是Controller
                {
                    var members = type.GetMethods();
                    foreach (var member in members)
                    {
                        if (member.ReturnType.Name == "ActionResult")//如果是Action
                        {
                            object[] attrs = member.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true);
                            if (attrs.Length > 0)
                            {

                                var ActionName = member.Name;
                                var ControllerName = member.DeclaringType.FullName.Substring(0, member.DeclaringType.FullName.Length - 10); // 去掉“Controller”后缀
                                var name = ControllerName + "." + ActionName;
                                var permission = new RolePermission() { PermissionName = name.ToLower() };

                                if (!string.IsNullOrEmpty(permission.PermissionName) && RolePermission.Actions.ContainsKey(permission.PermissionName) == false)
                                {

                                    var desc = (attrs[0] as System.ComponentModel.DescriptionAttribute).Description;
                                    var names = desc.Split('>');
                                    if (names.Length > 1)
                                    {
                                        permission.LableId = Admin.Controllers.HomeController.Menus[names[0]].LableId;
                                        permission.Description = names[1];
                                    }
                                    else permission.Description = desc;
                                    permission.RouteValues = new RouteValueDictionary(new { controller = ControllerName.Remove(0, ControllerName.LastIndexOf(".") + 1), action = ActionName, area = ControllerName.Remove(ControllerName.LastIndexOf(".Controllers")).Remove(0, 20) });
                                    RolePermission.Actions.Add(permission.PermissionName, permission);
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    public class DataMutiLanguageInterceptor : NHibernate.EmptyInterceptor
    {

        public override NHibernate.SqlCommand.SqlString OnPrepareStatement(NHibernate.SqlCommand.SqlString sql)
        {
            var lang = Thread.CurrentThread.CurrentUICulture.Name.Replace("-", "_");
            sql = sql.Replace("[Case]", "[Case_" + lang + "]").Replace("[Lable]", "[Lable_" + lang + "]");
            return base.OnPrepareStatement(sql);
        }

    }
}